<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="user.username"
        name="username"
        :label="names[user.type - 1]"
        placeholder="点击这里填写"
        :rules="[{ required: true, message: '请填写买号登录用户名' }]"
      />
      <van-field
        v-if="user.type == 1"
        v-model="user.level"
        is-link
        readonly
        name="level"
        label="淘宝等级"
        placeholder="请选择"
        :rules="[{ required: true, message: '请选择淘宝等级' }]"
        @click="popup.level = true"
      >
        <template #input>
          <van-image height="10" :src="select.level" v-if="select.level" />
        </template>
      </van-field>
      <van-popup v-model:show="popup.level" position="bottom" teleport="#app">
        <div class="bg-f padded-10">
          <div
            class="p-b-10"
            v-for="(item, index) in levels"
            @click="fnSelectLevel(item, index + 1)"
          >
            <van-image height="10" :src="item" />
          </div>
          <van-button type="primary" size="large" @click="onLevelConfirm"
            >确定</van-button
          >
          <!-- onLevelConfirm -->
        </div>
      </van-popup>
      <van-field
        v-if="user.type == 1 || user.type == 2"
        readonly
        name="level_image"
        label="等级截图"
      >
        <template #input>
          <van-uploader
            :after-read="afterRead"
            :max-count="1"
            v-model="level_image"
          >
          </van-uploader>
        </template>
      </van-field>

      <van-field
        v-if="user.type == 2"
        v-model="user.value"
        name="value"
        label="京享值"
        placeholder="点击这里填写"
        :rules="[{ required: true, message: '请填写京享值' }]"
      />

      <van-field
        v-model="select.city"
        is-link
        readonly
        name="area"
        label="收货城市"
        placeholder="点击选择省市区"
        @click="popup.city = true"
        :rules="[{ required: true, message: '请选择收货城市' }]"
      />
      <van-popup v-model:show="popup.city" position="bottom" teleport="#app">
        <van-area
          :area-list="areaList"
          @confirm="onConfirmCity"
          @cancel="popup.city = false"
        />
      </van-popup>
      <van-field name="gender" label="性别">
        <template #input>
          <van-radio-group v-model="user.gender" direction="horizontal">
            <van-radio name="1">男</van-radio>
            <van-radio name="2">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>

      <van-field
        v-model="select.consume"
        is-link
        readonly
        name="consume"
        label="消费层级"
        placeholder="请选择"
        @click="popup.consume = true"
        :rules="[{ required: true, message: '请选择消费层级市' }]"
      />
      <van-popup v-model:show="popup.consume" position="bottom" teleport="#app">
        <van-picker
          :columns="consumeList"
          @confirm="onConfirmConsume"
          @cancel="popup.consume = false"
        />
      </van-popup>

      <van-field
        v-model="select.label"
        is-link
        readonly
        name="label"
        label="人群标签"
        placeholder="请选择"
        @click="popup.label = true"
        :rules="[{ required: true, message: '请选择人群标签' }]"
      />
      <van-popup v-model:show="popup.label" position="bottom" teleport="#app">
        <van-picker
          :columns="labelList"
          @confirm="onConfirmLabel"
          @cancel="popup.label = false"
        />
      </van-popup>
      <van-field
        v-model="user.category"
        is-link
        readonly
        name="category"
        label="常购类目"
        placeholder="请选择"
        @click="popup.category = true"
        :rules="[{ required: true, message: '请选择常购类目' }]"
      />
      <van-popup
        v-model:show="popup.category"
        position="bottom"
        round
        :style="{ height: '20%' }"
        teleport="#app"
      >
        <div class="bg-f category">
          <van-checkbox-group
            v-model="select.category"
            class="p-b-10"
            direction="horizontal"
            :max="5"
          >
            <van-checkbox
              :name="item.id"
              shape="square"
              v-for="item in categoryList"
              class="p-b-10 p-r-10"
              >{{ item.name }}</van-checkbox
            >
          </van-checkbox-group>
          <van-button type="primary" size="large" @click="selectCheckbox" round
            >确定</van-button
          >
        </div>
      </van-popup>
    </van-cell-group>
    <div style="margin: 16px">
      <van-button
        loading
        round
        block
        type="primary"
        loading-text="提交中..."
        v-if="loading"
      />
      <van-button round block type="primary" native-type="submit" v-else>
         {{id ? '确定修改' : '提交'}}
      </van-button>
    </div>
  </van-form>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted } from "vue";
import { useRouter } from "vue-router";

import { areaList } from "@vant/area-data";
import { fnGetCategory } from "@/service/index";
import { useStore } from "@/stores/store";
import { uploadFile, getAccountData } from "@/service/account";
import { fnMsg,consumeList, labelList, levels } from "@/plugins/common";
type ICate = {
  name: string;
  id: number;
};

type ISelect = {
  city?: any,
  level?: String,
  level_image?: String,
  consume?: any,
  label?: any,
  category: any,
}

export default defineComponent({
  props: {
    type: {
      type: Number,
      required: true,
    },
    id: {
      type: String,
    },
  },
  setup(props: any) {
    const store = useStore(),
      router = useRouter(),
      { type, id } = props,
      loading = ref(false), level_image = ref<any>();
    const user = ref({
        type: type,
        username: "",
        level: 0,
        level_image: '',
        province: "",
        city: "",
        area: "",
        gender: "1",
        consume: 0,
        label: 0,
        category: "",
        value: 0
      }),
      select = ref<ISelect>({
        city: "",
        level: "",
        level_image: "",
        consume: '',
        label: '',
        category: [],
      }),
      popup = ref({
        level: false,
        city: false,
        consume: false,
        label: false,
        category: false,
      }),
      categoryList = ref<ICate[]>([]),
      names = ["买号用户名", "京东帐号", "拼多多帐号", "抖音帐号", "快手帐号"];
    // 等级选择
    const onLevelConfirm = () => {
      popup.value.level = false;
    };

    // 地址选择
    const onConfirmCity = (areaValues: any) => {
      let [province, city, area] = areaValues.map((item: any) => item.name);
      select.value.city = [province, city, area].join("/");
      (user.value.province = province),
        (user.value.city = city),
        (user.value.area = area);
      popup.value.city = false;
    };

    const fnSelectLevel = (image: string, index: number) => {
      select.value.level = image;
      user.value.level = index;
      onLevelConfirm();
    };

    const onConfirmConsume = (e: string) => {
      user.value.consume = consumeList.findIndex((item) => item == e) + 1;
      select.value.consume = e;
      popup.value.consume = false;
    };

    const onConfirmLabel = (e: string) => {
      user.value.label = labelList.findIndex((item) => item == e) + 1;
      select.value.label = e;
      popup.value.label = false;
    };

    // 上传截图
    const afterRead = (file: any) => {
      // 此时可以自行将文件上传至服务器
      select.value.level_image = file.file;
    };

    const selectCheckbox = () => {
      if (select.value.category.length > 0) {
        user.value.category = select.value.category
          .map(
            (item: number) =>
              categoryList.value.filter((i: ICate) => i.id == item)[0].name
          )
          .join(",");
        console.log(user.value.category, "");
        //    user.value.category = category;
      }
      popup.value.category = false;
    };

    const onSubmit = () => {
      loading.value = true;
      let _param: any = {};
      let { category, level_image, value, level, ...params } = user.value;
      _param = {
        uid: store.state.user.uid,
        category: select.value.category,
        ...params,
      };
      
      switch (parseInt(user.value.type)) {
        case 1:
          _param["level"] = level;
          _param["level_image"] = select.value.level_image;
          break;
        case 2:
          _param["value"] = value;
          _param["level_image"] = select.value.level_image;
          break;
      }

      console.log(params, "params");
      let param = new FormData(); // 创建form对象
      for (var i in _param) {
        param.append(i, _param[i]); // 添加form表单中其他数据
      }
      uploadFile(id ? "User/buynumEdit" : "User/buynumAdd", param).then((res: any) => {
        console.log(res);
        loading.value = false;
        if (res) {
          fnMsg(res.msg);
          if (res.status) {
            router.push({ name: "account_list" });
          }
        }
      });
    };

    const getCategory = () => {
      return new Promise((resolve) => {
      fnGetCategory().then((res) => {
        if (res) {
          categoryList.value = res.data;
          resolve(res.data);
        }
      });
      });
    };

    const getData = () => {
      return new Promise((resolve) => {
        getAccountData({ uid: store.state.user.uid, id: id }).then((res) => {
          if (res && res.status) {
            let {address,birthday,jq, ...params} = res.data;
            user.value = {...params};
            resolve(params);
          }
        });
      });
    };

    const initCategory = async () => {
      let cate = await getCategory();
      let data = await getData();
      let res = user.value.category.split(',').map(item => categoryList.value.filter(i => Number(item) == i.id)[0]);
      select.value.category = res.map(item => item.id);
      user.value.category = res.map(item => item.name).join(',');
      select.value.consume = consumeList[user.value.consume - 1];
      select.value.label = labelList[user.value.label - 1];
      select.value.city = user.value.province+user.value.city+user.value.area;
      if (user.value.level_image) {
        select.value.level_image = user.value.level_image;
        level_image.value = [{url: user.value.level_image}];
      } 
      if (user.value.type == 1) select.value.level = levels[user.value.level - 1]
    };

    onMounted(() => {
      if (id) {
        initCategory();
      } else {
        getCategory()
      }
    });

    return {
      id,
      user,
      levels,
      popup,
      names,
      loading,
      level_image,
      onSubmit,
      onLevelConfirm,
      fnSelectLevel,
      select,
      afterRead,
      onConfirmCity,
      areaList,
      consumeList,
      onConfirmConsume,
      labelList,
      onConfirmLabel,
      categoryList,
      selectCheckbox,
    };
  },
});
</script>

<style lang="less">
.upload {
  width: 80px;
  height: 80px;
  background-color: #f8f8f8;
  line-height: 80px;
  border-radius: 3px;
}
.category {
  padding: 15px;
}
</style>
